/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android framework
 * Create Time: 16-2-16 下午6:51
 */

package com.lenovo.framework.rest;

import com.lenovo.framework.R;
import com.lenovo.framework.biz.ContextManager;
import com.lenovo.framework.util.DLog;
import com.lenovo.framework.util.NetworkUtil;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * network observer used to
 * @author JeffreyHe
 * @version 1.0
 * @updated 26-一月-2016 15:53:50
 */
public abstract class NetworkObserver<T> extends Subscriber<T> {
    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        DLog.p(e);
        if(e == null){
            onFailure(ContextManager.context().getString(R.string.unknown_error));
        }else{
            if(e instanceof SocketTimeoutException) {
                onFailure(ContextManager.context().getString(R.string.networks_timeout));
            }else if(e instanceof ConnectException) {
                onFailure(ContextManager.context().getString(R.string.not_connected_to_network));
            }else if(e instanceof HttpException){
                //401 already handled
                if(((HttpException) e).code() != 401)
                    onFailure(e.getLocalizedMessage());
            }else {
                if (NetworkUtil.isNetworkAvailable(ContextManager.context())) {
                    onFailure(ContextManager.context().getString(R.string.network_error));
                } else {
                    onFailure(ContextManager.context().getString(R.string.not_connected_to_network));
                }
            }
        }
    }

    @Override
    public void onNext(T t) {
        if(t == null){
            onFailure(ContextManager.context().getString(R.string.unknown_error));
        }else{
            onSuccess(t);
        }
    }

    public abstract void onSuccess(T t);
    public abstract void onFailure(String tip);
}
